package urldownresources;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * URL 下载网络资源   例如：xx云，下载头像图片
 */
public class URLDemo02 {
    public static void main(String[] args) throws IOException {
        //1.下载地址
        URL url = new URL("https://p2.music.126.net/zuVGBtlzWBKRm8UATvIl6A==/109951162942914798.jpg?param=200y200");

        //2.连接到这个资源 HTTP
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        // 获取连接的输入流
        InputStream inputStream = urlConnection.getInputStream();
        // 指定存放文件位置及文件名
        FileOutputStream fos = new FileOutputStream("network-programmin/src/main/resources/涉川头像.jpg");
        // 输入流转为字节，再重新写入指定文件
        byte[] buffer = new byte[1024];
        int len;
        while((len = inputStream.read(buffer))!=-1){
            fos.write(buffer,0,len);//写出这个数据
        }

        //4.断开连接
        fos.close();
        inputStream.close();
        urlConnection.disconnect();
    }
}
